from django.shortcuts import render
import re
import random
import string
import redis
from captcha.image import ImageCaptcha
from rest_framework.views import APIView
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password,check_password
from rest_framework.response import Response
from .models import *
from tools.generate import jwt_div
# Create your views here.
class checkName(APIView):
    def get(self,request,username):
        if not username:
            return Response({'code':400,'msg':'用户名不能为空'})
        if not re.findall(r"[a-zA-Z][a-zA-Z0-9]{4,15}$",username):
            return Response({'code': 400, 'msg': '用户名规则不正确'})
        if Users.objects.filter(username=username).count()>0:
            return Response({'code': 400, 'msg': '用户名已存在'})
        return Response({'code':200,'msg':'校验用户名成功'})
class checkMobile(APIView):
    def get(self,request,mobile):
        if not mobile:
            return Response({'code':400,'msg':'手机号不能为空'})
        if not re.findall(r"1[3-9][0-9]{9}$",mobile):
            return Response({'code': 400, 'msg': '手机号规则不正确'})
        if Users.objects.filter(mobile=mobile).count()>0:
            return Response({'code': 400, 'msg': '手机号已存在'})
        return Response({'code':200,'msg':'手机号校验成功'})

class checkImage(APIView):
    def get(self,request,uuid):
        str_num=''.join(random.sample(string.ascii_letters+string.digits,6))
        r=redis.Redis(host='localhost',port=6379,db=0)
        r.set(uuid,str_num,ex=120)
        r.close()
        cap=ImageCaptcha()
        img=cap.generate(str_num)
        return HttpResponse(content_type='image/png',content=img)
    def post(self,request,uuid):
        code1=request.data.get('code')
        r=redis.Redis(host='localhost',port=6379,db=0)
        code2=r.get(uuid)
        r.close()
        if code2:
            aa=code2.decode()
        else:
            return Response({'code':400,'msg':'验证码过期'})
        if aa.lower() != code1:
            return Response({'code':400,'msg':'图片验证码错误'})
        return Response({'code':200,'msg':'图片验证码校验成功'})



class Register(APIView):
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        password2=request.data.get('password2')
        mobile=request.data.get('mobile')
        agree=request.data.get('agree')
        if not all([username,password,password2,mobile,agree]):
            return Response({'code':200,'msg':'字段不完整'})
        if not mobile:
            return Response({'code':400,'msg':'手机号字段不能为空'})
        if password != password2:
            return Response({'code':400,'msg':'两次输入的密码不一致'})
        if not agree:
            return Response({'code':400,'msg':"请勾选用户协议"})
        pwd=make_password(password)
        Users.objects.create(
            username=username,password=pwd,mobile=mobile
        )
        return Response({'code':200,'msg':'注册成功'})

from django.db.models import  Q
class Login(APIView):
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        user=Users.objects.filter(Q(username=username) | Q(mobile=username))
        if not user:
            return Response({'code':400,'msg':'用户不存在'})
        if not check_password(password,user[0].password):
            return Response({'code':400,'msg':'密码不一致'})
        token=jwt_div(user[0])
        return Response({
            'code':200,
             'msg':'登录成功',
            'token':token,
             'user':username,
             }
        )

class AddressViews(APIView):
    def get(self,request):
        a_data=Address.objects.all()
        a_list=[]
        for i in a_data:
            a_list.append({
                'id':i.id,
                'name':i.name,
                'mobile':i.mobile,
                'addss':i.addss,
            })
        return Response(a_list)
    def post(self,request):
        name=request.data.get('name')
        mobile=request.data.get('mobile')
        addss=request.data.get('addss')
        Address.objects.create(
            name=name,mobile=mobile,addss=addss
        )
        return Response({'code':200,'msg':'添加数据成功'})

class UpdateDel(APIView):
    def put(self,request,id):
        name = request.data.get('name')
        mobile = request.data.get('mobile')
        addss = request.data.get('addss')
        Address.objects.filter(id=id).update(
            name=name, mobile=mobile, addss=addss
        )
        return Response({'code': 200, 'msg': '修改数据成功'})
    def delete(self,request,id):
        Address.objects.filter(id=id).delete()
        return Response({'code':200,"msg":'删除从数据成功'})










